import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit"
import axios from "axios"

interface UserState {
	loading: boolean
	error: string | undefined
	token: string | undefined
}

const initialState: UserState = {
	loading: true,
	error: undefined,
	token: undefined,
}

export const signIn = createAsyncThunk(
	"user/signIn",
	async (
		params: {
			email: string
			password: string
		},
		thunkAPI
	) => {
		return axios.post(`/user/signIn`, {
			email: params.email,
			password: params.password,
		})
	}
)

export const userSlice = createSlice({
	name: "user",
	initialState,
	reducers: {
		fetchStart: state => {
			state.loading = true
		},
		fetchSuccess: (state, action) => {
			state.loading = false
			state.token = action.payload
			state.error = undefined
		},
		fetchFailed: (state, action: PayloadAction<string | undefined>) => {
			state.loading = false
			state.error = action.payload
		},
	},

	extraReducers: {
		[signIn.pending.type]: state => {
			state.loading = true
		},
		[signIn.fulfilled.type]: (state, action) => {
			state.loading = false
			state.token = action.payload
			state.error = undefined
		},
		[signIn.rejected.type]: (state, action: PayloadAction<string | undefined>) => {
			state.loading = false
			state.error = action.payload
		},
	},
})
